<template>
  <ul class="fx-count-scroll-item" ref="countScrollItemDom" :style="countScrollItemStyle">
    <transition-group :name="path">
      <li v-for="(item,index) in 10" :key="index" v-show="currentValue===index">
        {{ item - 1 }}
      </li>
    </transition-group>
  </ul>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, PropType, ref, SetupContext } from 'vue'
import { useModelWatch } from '@/base/hooks'
import { CountScrollPath } from '@/base/countScroll/countScroll.vue'

interface CountScrollItemProps {
  count: number;
  path: CountScrollPath;
}

export default defineComponent({
  name: 'fxCountScrollItem',
  props: {
    // 当前数值
    count: {
      type: Number as PropType<number>,
      required: true
    },
    // 当前数字值
    path: {
      type: String as PropType<CountScrollPath>,
      required: true
    }
  },
  setup (props: CountScrollItemProps, ctx: SetupContext) {
    const countScrollItemDom = ref<HTMLElement>()
    const childRect = ref<DOMRect>()
    const currentValue = ref<number>(props.count)
    useModelWatch(() => props.count, currentValue)

    // 初始化获取dom的style
    const init = () => {
      if (!countScrollItemDom.value) return null
      const child = countScrollItemDom.value?.children[currentValue.value]
      if (!child) return null
      childRect.value = child.getBoundingClientRect()
    }

    // 根据子类dom 设定父级style 隐藏其他
    const countScrollItemStyle = computed(() => {
      if (!childRect.value) return null
      return {
        width: `${childRect.value.width}px`,
        height: ctx.attrs.height,
        lineHeight: ctx.attrs.height
      }
    })

    onMounted(() => {
      init()
    })

    return {
      currentValue,
      countScrollItemDom,
      countScrollItemStyle
    }
  }
})
</script>
